import { http } from "@/utils/http";
import { getToken175, getToken43 } from "@/utils/token";

type Result = {
  message: string;
  data: any;
  code: number;
};

const taskRequest = <T>(method: string, url: string, data?: object) => {
  const token = getToken175();
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

const remoteRequest = <T>(method: string, url: string, data?: object) => {
  const remoteToken = getToken43();
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: remoteToken ? `Bearer ${remoteToken}` : undefined,
    },
  });
};

export const getAssetList = ({
  data,
  type = "asset",
}: {
  data: object;
  type: string;
}) => {
  return taskRequest<Result>("post", `/api/api/${type}/data`, data);
};

// ============ BAS威胁模拟模块 API ============

export const getStatisticsDashboard = (data?: {
  task_id?: string;
  start_date?: string;
  end_date?: string;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/statistics/dashboard",
    data
  );
};

export const getStatisticsTrends = (data?: {
  task_id?: string;
  days?: number;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/statistics/trends",
    data
  );
};

export const getStatisticsAttackCategories = () => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/statistics/attack_categories"
  );
};

export const getStatisticsVulnerabilityDetails = (data?: {
  task_id?: string;
  severity?: string;
  attack_category?: string;
  page?: number;
  page_size?: number;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/statistics/vulnerability_details",
    data
  );
};

export const getReportData = (data?: {
  task_id?: string;
  date_range?: { start_date?: string; end_date?: string };
  include_details?: boolean;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/report/get_data",
    data
  );
};

export const generateReport = (data?: {
  task_id?: string;
  output_path?: string;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/report/generate_html",
    data
  );
};

// 获取报告下载路径（当生成接口未直接返回file_path时，使用此接口获取）
// 构造报告下载URL（返回HTML内容，需用 <a> 直接下载/打开）
export const buildReportDownloadUrl = (filename: string) => {
  return `/api/threat_simulation/report/download?filename=${encodeURIComponent(
    filename
  )}`;
};

export const getScenarioList = (data?: {
  page?: number;
  page_size?: number;
  threat_type?: string;
  attack_category?: string;
  is_active?: boolean;
  is_builtin?: boolean;
  keyword?: string;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/scenario/list",
    data
  );
};

export const getScenarioDetail = (data?: {
  scenario_id?: number;
  scenario_code?: string;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/scenario/get",
    data
  );
};

export const addScenario = (data: {
  scenario_code: string;
  scenario_name: string;
  threat_type: string;
  attack_category: string;
  severity?: string;
  description?: string;
  payload_template?: string;
  http_config?: object;
  detection_strategies?: any[];
  require_dnslog?: boolean;
  is_active?: boolean;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/scenario/add",
    data
  );
};

export const updateScenario = (data: {
  scenario_id: number;
  scenario_name?: string;
  threat_type?: string;
  attack_category?: string;
  severity?: string;
  description?: string;
  payload_template?: string;
  require_dnslog?: boolean;
  is_active?: boolean;
  http_config?: object;
  detection_strategies?: any[];
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/scenario/update",
    data
  );
};

export const deleteScenario = (data: { scenario_id: number }) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/scenario/delete",
    data
  );
};

export const quickTestScenario = (data: {
  scenario_id: number;
  target_url: string;
  variables?: object;
  safe_mode?: boolean;
  timeout?: number;
  enable_waf_bypass?: boolean;
  bypass_strategies?: any[];
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/scenario/quick_test",
    data
  );
};

// 获取场景元数据统计
export const getScenarioMetadataStats = (data?: {
  include_inactive?: boolean;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/scenario/metadata_stats",
    data
  );
};

export const getTaskList = (data?: {
  page?: number;
  page_size?: number;
  status?: string;
  start_date?: string;
  end_date?: string;
}) => {
  return taskRequest<Result>("post", "/api/threat_simulation/task/list", data);
};

export const getTaskDetail = (data: { task_id: string }) => {
  return taskRequest<Result>("post", "/api/threat_simulation/task/get", data);
};

export const createTask = (data: {
  target_url: string;
  scenario_ids?: number[];
  task_name?: string;
  task_config?: object;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/task/create",
    data
  );
};

export const pauseTask = (data: { task_id: string }) => {
  return taskRequest<Result>("post", "/api/threat_simulation/task/pause", data);
};

export const resumeTask = (data: { task_id: string }) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/task/resume",
    data
  );
};

export const cancelTask = (data: { task_id: string }) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/task/cancel",
    data
  );
};

export const getResultList = (data?: {
  task_id?: string;
  page?: number;
  page_size?: number;
  severity?: string;
  status?: string;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/result/list",
    data
  );
};

export const getResultDetail = (data: { result_id: string }) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/result/get_detail",
    data
  );
};

// 获取防护有效性详情
export const getProtectionDetail = (result_id: string) => {
  return taskRequest<Result>("post", "/api/threat_simulation/result/detail", {
    result_id: result_id,
  });
};

export const getTaskLogs = (data: {
  task_id: string;
  level?: string; // all/info/warn/error
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/result/get_logs",
    data
  );
};

export const getTemplateList = (data?: {
  page?: number;
  page_size?: number;
  is_system?: boolean; // 可选，true=系统模板，false=自定义
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/template/list",
    data
  );
};

export const getTemplateDetail = (data: any) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/template/get",
    data
  );
};

export const createTemplate = (data: {
  template_name: string;
  scenario_ids: number[];
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/template/create",
    data
  );
};

export const createTaskFromTemplate = (data: {
  template_code: string;
  task_name?: string;
  target_url: string;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/template/create_task",
    data
  );
};

export const recommendTemplates = (data?: {
  target_url?: string;
  target_type?: string; // web/api/java
}) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/template/recommend",
    data
  );
};

export const getTemplateStatistics = (data?: { template_code?: string }) => {
  return taskRequest<Result>(
    "post",
    "/api/threat_simulation/template/statistics",
    data
  );
};

// ============ BAS恶意外联验证模块 API ============

export const testCeyeConnection = (data?: { config_name?: string }) => {
  return taskRequest<Result>("post", "/api/malicious/ceye/test", data);
};

export const getMaliciousAddressList = (data?: {
  page?: number;
  page_size?: number;
  threat_type?: string;
  is_active?: boolean;
  keyword?: string;
}) => {
  return taskRequest<Result>("post", "/api/malicious/address/list", data);
};

export const addMaliciousAddress = (data: {
  address: string;
  address_type?: string;
  threat_type?: string;
  threat_family?: string;
  confidence?: number;
  tags?: any[];
  description?: string;
}) => {
  return taskRequest<Result>("post", "/api/malicious/address/add", data);
};

export const deleteMaliciousAddress = (data: { ids: number[] }) => {
  return taskRequest<Result>("post", "/api/malicious/address/delete", data);
};

export const createVerificationTask = (data: {
  target_url: string;
  task_name?: string;
  target_description?: string;
  sample_size?: number;
  threat_type_filter?: string;
}) => {
  return taskRequest<Result>("post", "/api/malicious/task/create", data);
};

export const startVerificationTask = (data: { task_id: string }) => {
  return taskRequest<Result>("post", "/api/malicious/task/start", data);
};

export const getTaskProgress = (data: { task_id: string }) => {
  return taskRequest<Result>("post", "/api/malicious/task/progress", data);
};

export const getVerificationResult = (data: { task_id: string }) => {
  return taskRequest<Result>("post", "/api/malicious/task/result", data);
};

export const getVerificationTaskList = (data?: {
  page?: number;
  page_size?: number;
  status?: string;
}) => {
  return taskRequest<Result>("post", "/api/malicious/task/list", data);
};
